package org.whh.metadata.datasource.database;

import lombok.Data;
import org.whh.metadata.datasource.database.pojo.DataSourceParam;
import org.whh.metadata.util.URLCoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Version v1.0
 * @Author Ryan
 * @Date 2021/7/10
 * N-G-P
 */
@Data
public class MysqlDataSource extends DBDatasource{


    public static class MysqlDataSourceBuilder extends DataSourceParam {
        private MysqlDataSourceBuilder(){
        }

        @Override
        public MysqlDataSource build(){
            MysqlDataSource mysqlDataSource = new MysqlDataSource();
            mysqlDataSource.setDatabaseName(this.databaseName);
            mysqlDataSource.setPassword(this.password);
            mysqlDataSource.setPortNumber(this.portNumber);
            mysqlDataSource.setServerName(this.serverName);
            mysqlDataSource.setUrl(this.url);
            mysqlDataSource.setUser(this.user);
            mysqlDataSource.setDiverName(this.diverName);
            mysqlDataSource.setProperties(this.properties);
            return  mysqlDataSource;
        }

    }

    public static MysqlDataSourceBuilder builder(){
        return new MysqlDataSourceBuilder();
    }

    @Override
    public String buildUrl() {
        StringBuilder url = new StringBuilder(200);
        url.append("jdbc:mysql://");
        url.append(getServerName());
        url.append(":").append(getPortNumber());
        url.append("/").append(URLCoder.encode(getDatabaseName()));
        StringBuilder query = new StringBuilder(100);
        if(getProperties()!=null&&getProperties().size()>0){
            int i = 0;
            for(Object pro:getProperties().keySet()){
                if(i!=0){
                    query.append("&");
                }
                query.append(pro.toString());
                query.append("=");
                query.append(URLCoder.encode(getProperties().getProperty(pro.toString())));
                i++;
            }

        }
        if (query.length() > 0) {
            url.append("?");
            url.append(query);
        }
        return url.toString();
    }

    @Override
    public Connection getConnection() {
        Connection con = null;
        try {
            Class.forName(getDiverName());
            con = DriverManager.getConnection(this.getUrl(), getUser(), getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return con;
    }

    @Override
    public boolean testConnection() {
        return getConnection()!=null?true:false;
    }
}
